package org.getOffer.offer63;

import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.Collectors;

/**
 * @Author yu
 * @Date 2021/10/11
 */
public class Solution {

    public static void main(String[] args) {

        int[] arrays = {7,1,5,3,6,4};

        //int[] arrays = {7,6,4,3,1};

        Solution solution = new Solution();

        System.out.println(solution.maxProfit2(arrays));

    }

    public int maxProfit(int[] prices) {

        if (prices.length == 0) {
            return 0;
        }
//
//        int min = Arrays.stream(prices).min().getAsInt();
//
//        //List<Integer> list = Arrays.stream(prices).boxed().collect(Collectors.toList());
//
//        int[] temps = new int[prices.length];
//
//        boolean flag = false;
//
//        for (int i = 0, j = 0; i<prices.length; i++) {
//            if(prices[i] == min) {
//                flag = true;
//                continue;
//            }
//            if (flag) {
//                temps[j] = prices[i];
//                j++;
//            }
//        }
//
//        int max = Arrays.stream(temps).max().getAsInt();
//
//        return max == 0 ? 0 : max - min;

        int min = 0;

        int profit = 0;

        for (int j = 0; j<prices.length-1; j++) {
            min = prices[j];
            for (int i = j+1; i<prices.length; i++) {

                if (prices[i] - min > profit) {
                    profit = prices[i] - min;
                }

            }
        }

        return profit;

    }

    public int maxProfit2(int[] prices) {
        int cost = Integer.MAX_VALUE, profit = 0;
        for(int price : prices) {
            cost = Math.min(cost, price);
            profit = Math.max(profit, price - cost);
        }
        return profit;
    }

}
